//
//  ExecuteOrderViewController.m
//  ServiceDemo
//
//  Created by apple on 16/2/16.
//  Copyright (c) 2016年 HuaZhengInfo. All rights reserved.
//

#import "ExecuteOrderViewController.h"
#import "GrabOrderTableViewCell.h"
#import "DetailExeViewController.h"
#import "FirstDetailViewController.h"
#import "MyOrderListModel.h"
#import "MyOrderTableViewCell.h"
#import "FilterView.h"

@interface ExecuteOrderViewController ()<UITableViewDataSource,UITableViewDelegate,FilterViewDelegate>{

    UITableView * _mainTableView;
    NSMutableArray * _dataArray;
    NSMutableArray * _mainArray;
    NSMutableArray * _detailArray;
    
    NSString * _PAGEINDEX; // 页数
    int _page;
    NSString * _ROWNUM;  // 行数
}
@property (nonatomic, assign) BOOL pullHeader;
@property (nonatomic, strong) FilterView *filterView;
@property (nonatomic, strong) UIView *maskView;
@property (nonatomic, assign) BOOL filterViewShow;
@property (nonatomic, assign) BOOL filterRequest;
@property (nonatomic, copy) NSString *stateString;
@property (nonatomic, copy) NSString *cateString;
@property (nonatomic, copy) NSString *orderString;

@end

@implementation ExecuteOrderViewController


//懒加载
- (FilterView *)filterView {
    if (!_filterView) {
        _filterView = [FilterView filterView];
        _filterView.delegate = self;
        _filterView.frame = CGRectMake(SCR_W, 0, SCR_W-20, SCR_H-108);
//        [([[UIApplication sharedApplication] delegate]).window addSubview:_filterView];
        [self.view addSubview:_filterView];
    }
    return _filterView;
}

-(UIView *)maskView{
    if (!_maskView) {
        _maskView=[[UIView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H)];
        _maskView.backgroundColor=[UIColor blackColor];
        _maskView.alpha=0;
        UIGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(filterViewDisappear)];
        [_maskView addGestureRecognizer:tap];
    }
    return _maskView;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    self.filterViewShow = NO;
    self.view.backgroundColor = [UIColor whiteColor];
    UIButton *rightButton = [GDFactory creatUIButtonWithFrame:CGRectMake(0, 5, 30, 15) backImage:nil title:@"筛选" titleLableColcor:[UIColor whiteColor] titleLabelFont:[UIFont systemFontOfSize:15]];
    [rightButton addTarget:self action:@selector(clickRight) forControlEvents:UIControlEventTouchUpInside];
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithCustomView:rightButton];
    
    // 初始化
    _dataArray = [[NSMutableArray alloc] init];
    _mainArray = [NSMutableArray array];
    _detailArray = [NSMutableArray array];
    _PAGEINDEX = @"1";
    _page = 1;
    _ROWNUM = @"10";
    
    [self buildTableView];
    [self setupRefresh];
    [_mainTableView headerBeginRefreshing];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshData) name:@"OrderExecuteRefreshNotification" object:nil];
    
}

//notification selector
- (void)refreshData {
    [_mainTableView headerBeginRefreshing];
}

//点击筛选
- (void)clickRight {
    if (!self.filterViewShow) {
        [self.view insertSubview:self.maskView belowSubview:self.filterView];
        self.filterViewShow = !self.filterViewShow;
        [UIView animateWithDuration:0.3 animations:^{
            //        [([UIApplication sharedApplication].delegate).window insertSubview:self.maskView belowSubview:self.filterView];
            self.filterView.frame = CGRectMake(20, 0, SCR_W-20, SCR_H-108);
            self.maskView.alpha = 0.4;
        }];
    } else {
        [self filterViewDisappear];
    }
    
}

- (void)filterViewDisappear {
    [UIView animateWithDuration:0.3 animations:^{
        self.filterView.frame = CGRectMake(SCR_W, 0, SCR_W-20, SCR_H-108);
        [self.maskView removeFromSuperview];
        self.filterView = nil;
    }];
    self.filterViewShow = !self.filterViewShow;
}

#pragma mark -- filterViewDelegate
- (void)filterActionWithStateArray:(NSArray *)stateArray cateArray:(NSArray *)cateArray orderString:(NSString *)orderString{
    NSString *stateString = stateArray[0];
    NSString *cateString = [cateArray componentsJoinedByString:@","];
    if ([stateString isEqualToString:@"不限"]) {
        stateString = @"";
    }
    if ([stateString isEqualToString:@"未完成"]) {
        stateString = @"0";
    }
    if ([stateString isEqualToString:@"已完成"]) {
        stateString = @"1";
    }
    if ([cateString isEqualToString:@"不限"]) {
        cateString = @"";
    }
//    NSLog(@"%@ %@", stateString, cateString);
    _PAGEINDEX = @"1";
    _page = 1;
    [self filterRequestDataWithState:stateString cate:cateString order:orderString];
}


#pragma mark -- 请求数据
- (void)requestData{
    
    [_dataArray removeAllObjects];
    
    NSArray * keyArray = @[@"USER_ID",@"USER_CODE",@"MODULE",@"COMPLETED",@"TYPE",@"PAGEINDEX",@"ROWNUM"];
    
    NSArray * valueArray = @[@"1219",@"00086554",@"INSPECTION",@"",@"",_PAGEINDEX,_ROWNUM];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,MyOrderList_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        [_mainTableView headerEndRefreshing];
        [_mainTableView footerEndRefreshing];
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dict in array) {
            
            MyOrderListModel *  model = [[MyOrderListModel alloc] initWithDict:dict];
            
            [_dataArray addObject:model];
        }
        
        if ([_PAGEINDEX isEqualToString:@"1"]) {
            [_detailArray removeAllObjects];
            
        }
        for (MyOrderListModel * model in _dataArray) {
            [_detailArray addObject:model];
            
        }
        _mainArray = [_detailArray copy];
        [_mainTableView reloadData];
    } withTag:101];
    
//    _mainArray = [NSMutableArray arrayWithObjects:@"B区地下室墙面裂缝",@"B区地下车库入口标识缺失",@"B-2-01更换水龙头", nil];
//    _detailArray = [NSMutableArray arrayWithObjects:@"维修类订单A20160101",@"维修类订单A20160101",@"维修类订单A20160101", nil];
}

#pragma mark -- 筛选请求数据
- (void)filterRequestDataWithState:(NSString *)state cate:(NSString *)cate order:(NSString *)order {
    if (!state) {
        [MBProgressHUD HUDShowMessage:@"请选择订单状态" addedToView:self.view];
        return;
    }
    if (!cate) {
        [MBProgressHUD HUDShowMessage:@"请选择问题类型" addedToView:self.view];
        return;
    }
    
    [_dataArray removeAllObjects];
    self.stateString = state;
    self.cateString = cate;
    self.orderString = order;
    
    NSArray * keyArray = @[@"USER_ID",@"USER_CODE",@"MODULE",@"COMPLETED",@"TYPENAME",@"ORDERGUID",@"PAGEINDEX",@"ROWNUM"];
    
    NSArray * valueArray = @[@"1219",@"00086554",@"INSPECTION",state,cate,order,_PAGEINDEX,_ROWNUM];
    NSDictionary * dict = [NSDictionary dictionaryWithObjects:valueArray forKeys:keyArray];
    NSString * urlStr = [NSString stringWithFormat:@"%@%@",Base_URL,OrderFilter_URL];
    
    HZNetWorkAgent *agent = [HZNetWorkAgent shareInstance];
    [agent requestUrl:urlStr param:dict baseUrl:@"" withRequestMethod:HZRequestMethodPost withCompletionWithSuccess:^(HZBaseRequest *http, BOOL isSuccess) {
        _filterRequest = YES;
        [_mainTableView headerEndRefreshing];
        [_mainTableView footerEndRefreshing];
        NSMutableArray * array = [http.returnArray mutableCopy];
        for (NSDictionary * dict in array) {
            
            MyOrderListModel *  model = [[MyOrderListModel alloc] initWithDict:dict];
            
            [_dataArray addObject:model];
        }
        
        if ([_PAGEINDEX isEqualToString:@"1"]) {
            [_detailArray removeAllObjects];
            
        }

        for (MyOrderListModel * model in _dataArray) {
            [_detailArray addObject:model];
            
        }
        _mainArray = [_detailArray copy];
        [_mainTableView reloadData];
        if (self.filterViewShow) {
            [self filterViewDisappear];
        }
    } withTag:101];
    
}


- (void)buildTableView{
    
    _mainTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, SCR_W, SCR_H - 64) style:UITableViewStylePlain];
    _mainTableView.delegate = self;
    _mainTableView.dataSource = self;
    _mainTableView.rowHeight = SCR_H/9;
    _mainTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _mainTableView.tableFooterView = [[UIView alloc] init];
    [_mainTableView registerNib:[UINib nibWithNibName:@"MyOrderTableViewCell" bundle:nil] forCellReuseIdentifier:@"MyOrderTableViewCellId"];
    
    [self.view addSubview:_mainTableView];
    
    
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    if (!_mainArray || _mainArray.count == 0) {
        _mainArray = [_detailArray copy];
    }
//    return _mainArray.count;
    return _mainArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
//    NSString * ID = @"GD";
    MyOrderTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:@"MyOrderTableViewCellId" forIndexPath:indexPath];
//    if (cell == nil) {
//        cell = [[MyOrderTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:ID];
//        
//    }
    cell.model = _mainArray[indexPath.row];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{

    FirstDetailViewController * firstVC = [[FirstDetailViewController alloc] init];
    MyOrderListModel * model = _mainArray[indexPath.row];
    firstVC.GUID = model.GUID;
    firstVC.ID = model.ID;
    [self.navigationController pushViewController:firstVC animated:YES];
}

#pragma mark --- 刷新
- (void)setupRefresh{
//    _mainTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefreshing)];
//    _mainTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefreshing)];
    [_mainTableView addHeaderWithTarget:self action:@selector(headerRefreshing)];
    [_mainTableView addFooterWithTarget:self action:@selector(footerRefreshing)];

}

- (void)headerRefreshing{
    
    self.pullHeader = YES;
    _PAGEINDEX = @"1";
    _page = 1;
    if (self.filterRequest) {
        [self filterRequestDataWithState:self.stateString cate:self.cateString order:self.orderString];
    } else {
        [self requestData];
    }
}

- (void)footerRefreshing{
    self.pullHeader = NO;
    _page ++;
    _PAGEINDEX = [NSString stringWithFormat:@"%d",_page];
    [_dataArray removeAllObjects];
    if (self.filterRequest) {
        [self filterRequestDataWithState:self.stateString cate:self.cateString order:self.orderString];
    } else {
        [self requestData];
    }
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}


@end
